package xmu.crms.config;

import io.jsonwebtoken.Claims;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptorAdapter;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import xmu.crms.config.security.JwtUser;
import xmu.crms.config.security.SecurityConstant;
import xmu.crms.util.JwtUtil;

/**
 *
 *
 * @author status200
 * @date 2017/12/25
 */
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {


    private String jwtHeader = SecurityConstant.JWT_HEADER;

    @Override
    public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
        stompEndpointRegistry
                // websocket连接端点
                .addEndpoint("/ILoveOOAD")
                // 允许跨域连接
                .setAllowedOrigins("*");
    }


    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        // 推送消息前缀
        registry.enableSimpleBroker("/queue", "/topic");
        // 订阅消息前缀
        registry.setApplicationDestinationPrefixes("/app");
    }

    /**
     * 此处配置websocket的安全
     *
     * @param registration
     */
    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.interceptors(new ChannelInterceptorAdapter() {
            @Override
            public Message<?> preSend(Message<?> message, MessageChannel channel) {
                StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);

                if(StompCommand.CONNECT.equals(accessor.getCommand())) {
                    // 获取AuthToken
                    String authString = accessor.getFirstNativeHeader(jwtHeader);

                    if(authString != null && authString.startsWith(SecurityConstant.JWT_HEADER_PREFIX)) {
                        Claims claims = JwtUtil.getClaimsFromAuthString(authString);

                        if(claims != null) {

                            JwtUser userDetails = new JwtUser();
                            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
                            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                            accessor.setUser(authenticationToken);
                        }
                    }

                }

                return message;
            }

        });
    }
}
